package com.zlx.controller;

import com.alibaba.fastjson.JSONObject;
import com.zlx.constants.Constant;
import com.zlx.utils.EmailUtil;
import com.zlx.utils.RandomUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author 周罗校
 * @Description 发送邮件
 * @ClassName EmailServlet
 * @date 2020.09.27 11:02:39
 * 该版权归周罗校所有，最终解释权以官方为准
 */

@WebServlet("/email/*")
public class EmailServlet extends BaseServlet{
    /**
     * @Author 周罗校
     * @Description 发送邮件
     * @Param [request, response]
     * @return void
     * @Date 2020.09.27 11:16:20
     **/
    protected void sendEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取email地址
        String emailAddr = request.getParameter("emailAddr");
        //随机生成验证码
        String random = RandomUtil.getRandom();
        try {
            //发送邮邮件
            EmailUtil.sendEmail(emailAddr,random);
            //把验证码放到session
            HttpSession session = request.getSession();
            session.setAttribute(Constant.EMAIL_CODE,random);
            //设置session的有限时间为60s
//            session.setMaxInactiveInterval(60);
            //响应成功
            /*String s = JSONObject.toJSONString(1);*/
            response.getWriter().write(JSONObject.toJSONString(1));
        } catch (Exception e) {
            e.printStackTrace();
            //发送邮件失败
            response.getWriter().write(JSONObject.toJSONString(0));
        }
    }
}
